//
//  TYZFMDBTool.m
//  kanhujia
//
//  Created by lxl on 2018/5/15.
//  Copyright © 2018年 lxl. All rights reserved.
//

#import "TYZFMDBTool.h"
#import <FMDB.h>

@interface TYZFMDBTool ()
/**
 *  当前时间
 */
@property(nonatomic, copy) NSString *currentTime;
/**
 *  数据库引用
 */
@property(nonatomic, strong) FMDatabase *dataBase;
@end
@implementation TYZFMDBTool
+ (instancetype)sharedFMDBTool {
    static TYZFMDBTool *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        instance = [[TYZFMDBTool alloc] init];
        
    });
    return instance;
}
- (FMDatabase *)dataBase {
    if (_dataBase == nil) {
        _dataBase = [FMDatabase databaseWithPath:BaseInfo.sqlite];
    }
    return _dataBase;
}
- (NSString *)currentTime {
    return [[NSDate date] formatterDate:@"yyyy-MM-dd HH:mm"];
}
@end

@implementation TYZRemenberModel
#define TableName     @"Browser"
#define TableHeader   @"(userAccount, password)"
#define TableContent  @"(?, ?)"
#define TableUpdate   @"password = ? WHERE  userAccount = ?"
+ (instancetype)sharedFMDBTool {
    static TYZRemenberModel *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken,^{
        instance = [[TYZRemenberModel alloc] init];
        [instance createDataBase];
    });
    return instance;
}
- (void)createDataBase {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:BaseInfo.sqlite] == NO) {
        if ([self.dataBase open]) {
            // 建立Browser表
            BOOL result = [self.dataBase executeUpdate:[NSString stringWithFormat:@"CREATE TABLE %@ %@", TableName, TableHeader]];
            if (result) {
                NSLog(@"成功打开数据库");
            } else {
                NSLog(@"创建数据库的时候出错");
            }
            [self.dataBase close];
        } else {
            NSLog(@"打开数据库的时候出错");
        }
    }
}
// 插入多条数据
- (void)insertWithArray:(NSArray<TYZRemenberModel *> *)modelArray {
    if ([self.dataBase open]) {
        [modelArray enumerateObjectsUsingBlock:^(TYZRemenberModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self insertCodeWithModel:obj];
        }];
        [self.dataBase close];
    }
}
// 插入一条数据(插入前先查询，如果有则删除再插入)
- (void)insertWithModel:(TYZRemenberModel *)model {
    if ([self.dataBase open]) {
        [self insertCodeWithModel:model];
        [self.dataBase close];
    }
}
- (void)insertCodeWithModel:(TYZRemenberModel *)model {
    // 1.执行查询语句
    FMResultSet *resultSet = [self.dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@", TableName]];
    // 2.遍历结果
    while ([resultSet next]) {
        NSString *string = [resultSet stringForColumn:@"userAccount"];
        if ([string isEqualToString:model.userAccount]) {
            [self deleteCodeWithUserAccount:model.userAccount];
        }
    }
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO %@ %@ VALUES %@;", TableName, TableHeader, TableContent];
    BOOL result = [self.dataBase executeUpdate:sql, model.userAccount, model.password];
    if (result) {
        NSLog(@"插入成功");
    } else {
        NSLog(@"插入错误");
    }
}
// 删除所有数据
- (void)delete {
    if ([self.dataBase open]) {
        [self.dataBase executeUpdate:[NSString stringWithFormat:@"DROP TABLE IF EXISTS %@;", TableName]];
        [self.dataBase executeUpdate:[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ %@;", TableName, TableHeader]];
        [self.dataBase close];
    }
}
// 删除具体的记住编码的数据
- (void)deleteWithUserAccount:(NSString *)userAccount {
    if ([self.dataBase open]) {
        [self deleteCodeWithUserAccount:userAccount];
        [self.dataBase close];
    }
}
- (void)deleteCodeWithUserAccount:(NSString *)userAccount {
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@ WHERE userAccount = ?", TableName];
    if ([self.dataBase executeUpdate:sql, userAccount]) {
        NSLog(@"删除成功");
    } else {
        NSLog(@"删除失败");
    }
}
// 根据模型的记住编码更新数据
- (void)updateDataWithModel:(TYZRemenberModel *)model {
    if ([self.dataBase open]) {
        NSString *sql = [NSString stringWithFormat:@"UPDATE %@ SET %@", TableName, TableUpdate];
        BOOL result = [self.dataBase executeUpdate:sql, model.userAccount, model.password];
        if (result) {
            NSLog(@"更新成功");
        } else {
            NSLog(@"更新失败");
        }
        [self.dataBase close];
    }
}
// 根据记住的编码查询整个模型
- (TYZRemenberModel *)queryWithUserAccount:(NSString *)userAccount {
    TYZRemenberModel *model = [[TYZRemenberModel alloc] init];
    BOOL isTure = NO;
    if ([self.dataBase open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [self.dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@", TableName]];
        // 2.遍历结果
        while ([resultSet next]) {
            NSString *string = [resultSet stringForColumn:@"userAccount"];
            if ([string isEqualToString:userAccount]) {
                isTure = YES;
                model.userAccount = userAccount;
                model.password = [resultSet stringForColumn:@"password"];
            }
        }
        [self.dataBase close];
    }
    if (isTure) {
        return model;
    }
    return nil;
}
// 查询所有
- (NSArray<TYZRemenberModel *> *)query {
    NSMutableArray *arrayM = [NSMutableArray array];
    if ([self.dataBase open]) {
        // 1.执行查询语句
        FMResultSet *resultSet = [self.dataBase executeQuery:[NSString stringWithFormat:@"SELECT * FROM %@", TableName]];
        // 2.遍历结果
        while ([resultSet next]) {
            TYZRemenberModel *model = [[TYZRemenberModel alloc] init];
            model.userAccount = [resultSet stringForColumn:@"userAccount"];
            model.password = [resultSet stringForColumn:@"password"];
            [arrayM addObject:model];
        }
        [self.dataBase close];
    }
    return [arrayM mutableCopy];
}
@end
